package com.example.zkweixiu.app.fragment;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonAdapter;
import com.example.zkweixiu.app.R;

import com.example.zkweixiu.app.activity.Unit3Activity;
import com.example.zkweixiu.app.bean.TaskBean;
import com.example.zkweixiu.app.bean.UnitListBean;
import com.example.zkweixiu.app.pro.PublicPro;

import com.example.zkweixiu.app.service.MyService;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

public class HomeFragment2 extends Fragment {

    private TextView tv_tiao;
    private UnitListBean unitListBean;
    private CommonAdapter<UnitListBean.DataBean.RowsBean> commonAdapter;
    private CommonAdapter<UnitListBean.DataBean.RowsBean> commonAdapter2;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 200:
                    initList();
                    list_task.setAdapter(commonAdapter);
                    if (sw_out != null) {
                        sw_out.setRefreshing(false);
                    }
                    break;
            }
        }
    };


    /**
     * 初始化listView
     *
     * */
    private void initList() {
        commonAdapter = new CommonAdapter<UnitListBean.DataBean.RowsBean>(getActivity(), R.layout.list_item1, unitListBean.getData().getRows()) {

            @Override
            public void onUpdate(BaseAdapterHelper helper, final UnitListBean.DataBean.RowsBean item, int position) {

                if (TextUtils.isEmpty(item.getSetVolName()) || "无".equals(item.getSetVolName())){
                    helper.setText(R.id.tv_user_name1,item.getUserName());
                }else {
                    helper.setText(R.id.tv_user_name1,item.getSetVolName());
                    //sadsa.setText(item.getSetVolName());

                }

                helper.setText(R.id.tv_name,item.getSetAlias());
                helper.setText(R.id.tv_user_name2,item.getUserName());

                if ("100".equals(item.getSetStatus())) {
                    helper.setText(R.id.tv_status,"设备离线");

                }else if ("0".equals(item.getSetStatus())) {
                    helper.setText(R.id.tv_status,"设备关机");

                }else  {
                    helper.setText(R.id.tv_status,"设备开机");

                }

                helper.setOnClickListener(R.id.rl_kz, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
/*                        PublicPro.IP_UUID.clear();
                        PublicPro.IP_UUID.put(item.getSetUuid(),item.getSetIp());
                        PublicPro.ISSERVICE = true;
                        Intent intent = new Intent(getActivity(), Unit3Activity.class);
                        intent.putExtra("ip", item.getSetIp());
                        intent.putExtra("uuid", item.getSetUuid());
                        intent.putExtra("user_t", item.getEnergy()+"");
                        intent.putExtra("status",item.getSetStatus()+"");
                        intent.putExtra("unit_name", item.getSetAlias());
                        intent.putExtra("trusteeship", item.getTrusteeship());
                     //   intent.putExtra("gongshui", split[6]);
                        startActivity(intent);*/

                        //清空集合
                        //集合赋值
                        //服务置位可运行
                        // 传入设定温度
                        //intent.putExtra("user_t", item.getEnergy()+"");
                        // intent.putExtra("ip", item.getSetIp());
                        // intent.putExtra("uuid", item.getSetUuid());
                        // intent.putExtra("status",item.getSetStatus()+"");

                        //跳转页面
                        //-------------------------------------------------


                        //启动服务

                        //监听服务返回的数据

                        //把数据设置到页面中


                    }
                });


            }
        };

    }


    public  boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceInfoList = manager.getRunningServices(200);
        if (serviceInfoList.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningServiceInfo info : serviceInfoList) {
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }
    private SwipeRefreshLayout sw_out;
    private ListView list_task;
    private TextView sadsa;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //先执行
        View view = inflater.inflate(R.layout.fragment2, container, false);
        return view;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        sw_out = view.findViewById(R.id.sw_out);

        list_task = view.findViewById(R.id.list_task);



        sw_out.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {  //监听下拉刷新
            @Override
            public void onRefresh() {
                //
                getUnitList();
            }
        });


/*        tv_tiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), DeviceActivity.class);
                startActivity(intent);
            }
        });*/
    }

    @Override
    public void onStart() {
        super.onStart();
        getUnitList();

    }

    private void getUnitList() {
        ///weixiu/unit_list

        OkHttpUtils
                .get()
                .url(PublicPro.UNIT_LIST)
                .addParams("wx_uuid", PublicPro.userBean.getData().getGuaUuid())
                .addParams("page", "1")
                .addParams("rows", "100")
                .addParams("token", PublicPro.userBean.getData().getGuaToken())
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                        if (sw_out != null) {
                            sw_out.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);
                        unitListBean = new Gson().fromJson(response,UnitListBean.class);

                        if (unitListBean.getStatus() == 200) {

                          handler.sendEmptyMessage(200);
                        }else {
                            if (sw_out != null) {
                                sw_out.setRefreshing(false);
                            }
                            Toast.makeText(getActivity(), unitListBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
}
